package com.tbit.uqbike.service.business.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.object.pojo.Account;
import com.tbit.uqbike.object.pojo.Battery;
import com.tbit.uqbike.object.pojo.dto.BatteryQueryDTO;
import com.tbit.uqbike.object.pojo.dto.BmsBatteryQueryDTO;
import com.tbit.uqbike.object.pojo.vo.BatteryVO;
import com.tbit.uqbike.object.pojo.vo.BmsBatteryVO;
import com.tbit.uqbike.object.pojo.vo.BmsConfigVO;
import com.tbit.uqbike.object.pojo.vo.CurrentBattery;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.BatteryService;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.core.BatteryModelDao;
import com.tbit.uqbike.webmanager.dao.core.BmsDao;
import com.tbit.uqbike.webmanager.dao.core.RideLogDao;
import com.tbit.uqbike.webmanager.dao.data.BatteryDao;
import com.tbit.uqbike.webmanager.dao.log.PowerChangeLogDao;
import com.tbit.uqbike.webmanager.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 电池信息表(Battery)表服务实现类
 *
 * @author jing
 * @since 2020-12-04 13:49:31
 */
@Service("batteryService")
public class BatteryServiceImpl implements BatteryService {
    @Resource
    private BatteryDao batteryDao;
    @Autowired
    private BmsDao bmsDao;
    @Autowired
    private PowerChangeLogDao powerChangeLogDao;
    @Autowired
    private RideLogDao rideLogDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private BatteryModelDao BatteryModelDao;

    /**
     * 通过ID查询单条数据
     *
     * @param batteryId 主键
     * @return 实例对象
     */
    @Override
    public Battery queryById(Integer batteryId) {
        return this.batteryDao.queryById(batteryId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Battery> queryAllByLimit(int offset, int limit) {
        return this.batteryDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param battery 实例对象
     * @return 实例对象
     */
    @Override
    public Battery insert(Battery battery) {
        this.batteryDao.insert(battery);
        return battery;
    }

    /**
     * 修改数据
     *
     * @param battery 实例对象
     * @return 实例对象
     */
    @Override
    public Battery update(Battery battery) {
        this.batteryDao.update(battery);
        return this.queryById(battery.getBatteryId());
    }

    /**
     * 通过主键删除数据
     *
     * @param batteryId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer batteryId) {
        return this.batteryDao.deleteById(batteryId) > 0;
    }

    @Override
    public Boolean queryByBatteryNO(String batteryNO) {
        return 1 == batteryDao.getByBatteryNO(batteryNO);
    }

    @Override
    public void insertBatch(List<Battery> batteries) {
        batteryDao.insertBatch(batteries);
    }

    @Override
    public void updateByBattery(Battery battery) {
        batteryDao.update(battery);
    }

    @Override
    public List<Battery> queryPage(Battery battery) {
        PageHelper.startPage(battery.getPage().getPageNO(), battery.getPage().getRowCount());
        return batteryDao.queryAll(battery);
    }

    @Override
    public PageResult<BatteryVO> queryPageBattery(BatteryQueryDTO BatteryQueryDTO) {
        Integer page = BatteryQueryDTO.getPage();
        Integer size = BatteryQueryDTO.getSize();
        Date startTime = BatteryQueryDTO.getStartTime();
        Date endTime = BatteryQueryDTO.getEndTime();
//        PageInfo<BatteryVO> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> BatteryModelDao.queryBatteryList(BatteryQueryDTO));
        List<BatteryVO> bmsBatteryList = BatteryModelDao.queryBatteryList(BatteryQueryDTO);
        // 用来做时间筛选
        List<BatteryVO> bmsBatteryListVo = new ArrayList<>();
        if (bmsBatteryList != null && bmsBatteryList.size() > 0) {
            List<Integer> collect = bmsBatteryList.stream().map(b -> b.getAccountId()).collect(Collectors.toList());
            List<Account> byAccountIds = accountDao.getByAccountIds(collect);
            Map<Integer, String> collect1 = byAccountIds.stream().collect(Collectors.toMap(Account::getAccountId, Account::getName));
            List<String> batteryNOS = bmsBatteryList.stream().map(b -> b.getBatteryNo()).collect(Collectors.toList());
            List<CurrentBattery> currentAndPrevious = powerChangeLogDao.getCurrentAndPrevious(batteryNOS);
            Map<String, CurrentBattery> currentAndPreviousMap = currentAndPrevious.stream().collect(Collectors.toMap(CurrentBattery::getBatteryNO, v -> v));
            for (BatteryVO BatteryVO : bmsBatteryList) {
                BatteryVO.setAccountName(collect1.get(BatteryVO.getAccountId()));
                CurrentBattery currentBattery = currentAndPreviousMap.get(BatteryVO.getBatteryNo());
                if (currentBattery != null) {
                    if (startTime != null && endTime != null){
                        String currentChangeTime = currentBattery.getCurrentChangeTime();
                        Date currentChangeTimeDate = null;
                        if (currentChangeTime != null){
                            try {
                                currentChangeTimeDate = DateUtils.parseDate(currentChangeTime, "yyyy-MM-dd HH:mm:ss");
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        // currentChangeTime 要在 startTime 和  endTime 范围内 currentChangeTime 的格式为 yyyy-MM-dd HH:mm:ss
                        if (currentChangeTimeDate != null && currentChangeTimeDate.after(startTime) && currentChangeTimeDate.before(endTime)) {
                            bmsBatteryListVo.add(BatteryVO);
                        }
                    }else {
                        bmsBatteryListVo.add(BatteryVO);
                    }
                    BatteryVO.setCurrentChangeTime(currentBattery.getCurrentChangeTime());
                    BatteryVO.setCurrentOldSoc(currentBattery.getCurrentOldSoc());
                    BatteryVO.setCurrentNewSoc(currentBattery.getCurrentNewSoc());
                    BatteryVO.setPreviousChangeTime(currentBattery.getPreviousChangeTime());
                    BatteryVO.setPreviousOldSoc(currentBattery.getPreviousOldSoc());
                    BatteryVO.setPreviousNewSoc(currentBattery.getPreviousNewSoc());
                    BatteryVO.setConsumptionSoc();
                    if (currentBattery.getCurrentChangeTime() != null) {
                        double currentMileage = rideLogDao.getCurrentMileage(currentBattery);
                        BatteryVO.setCurrentMileage(currentMileage);
                    }
/*                    if (currentBattery.getPreviousChangeTime() != null){
                        double previousMileage = rideLogDao.getPreviousMileage(currentBattery);
                        bmsBatteryVO.setPreviousMileage(previousMileage);
                    }*/
                }else {
                    bmsBatteryListVo.add(BatteryVO);
                }
            }
        }
        int num = 1;
        if (bmsBatteryListVo.size() % size == 0){
            num = bmsBatteryListVo.size() / size;
        }else {
            num = bmsBatteryListVo.size() / size + 1;
        }
        // 动态取 bmsBatteryListVo 的满足 第几页第几条的list
        List<BatteryVO> bmsBatteryListVoList = new ArrayList<>();
        bmsBatteryListVoList = bmsBatteryListVo.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
        return new PageResult<>(page, size, (long)bmsBatteryListVo.size(), num, bmsBatteryListVoList);
    }
}